<template>
	<div>
		<el-form-item
			label="题干"
			prop="questionTitle"
			:rules="{
				required: true,
				message: '请输入题干',
				trigger: ['blur', 'change']
			}"
		>
			<template>
				<el-input v-model.trim="questionForm.questionTitle" maxlength="2000">
					<i
						slot="suffix"
						@click="handleEdit(questionForm.questionTitle,'questionTitle')"
						class="el-icon-edit-outline icons"
					/>
				</el-input>
				<span class="tips m-t15">Tips：选词填空题需要在题干的每个填空处放上（）</span>
			</template>
		</el-form-item>
		<el-form-item label="选项" required>
			<div class="options-group">
				<el-form-item
					v-for="(item, index) in questionForm.optionList"
					:key="item.key+item.optionSeq"
					:prop="'optionList.' + index"
					:rules="{
						required: true, validator:checkOption, trigger: ['blur', 'change']
					}"
				>
					<select-options
						:value="item"
						:index="index"
						:is-show-seq="false"
						:is-editor="false"
						:is-add="index===0"
						:is-del="index>1"
						:max-length="100"
						@add="add"
						@del="del"
					/>
				</el-form-item>
			</div>
			<span class="tips">Tips：选项的数量不得少于题干中（）的数量</span>
		</el-form-item>
		<el-form-item
			label="答案"
			required
			prop="answer"
			:rules="{
				required: true, message: '请设置答案', trigger: ['blur', 'change']
			}"
		>
			<el-input
				ref="answerRef"
				v-model.trim="questionForm.answer"
				readonly
				placeholder="点击设置答案"
				@focus="handleIsShowSetAnswerDialog"
			/>
		</el-form-item>
		<set-answer-dialog
			v-if="isShowSetAnswerDialog"
			:is-show-set-answer-dialog.sync="isShowSetAnswerDialog"
			:question-answer="questionForm.answer"
			:question-content-title="questionForm.questionTitle"
			:question-answer-list="questionForm.optionList"
			@set-answer="setAnswer"
			@cancel="isShowSetAnswerDialog = false"
		/>
	</div>
</template>
<script >
	import SelectOptions from "../../async/select-options.vue";
	import SetAnswerDialog from "./set-answer-dialog.vue";
	export default {
		name: "q-blank-edit",
		props: {
			value: {
				type: Object,
				default: () => {}
			}
		},
		components: {
			SelectOptions,
			SetAnswerDialog
		},
		data() {
			return {
				questionForm: {},
				isShowSetAnswerDialog: false
			};
		},
		watch: {
			value: {
				immediate: true,
				deep: true,
				handler(val) {
					this.questionForm = JSON.parse(JSON.stringify(val));;
					if (!val.optionList || !val.optionList.length) {
                        this.$set(this.questionForm,'answer','');
						this.$set(this.questionForm, "optionList", [
							{
								optionSeq: 'A',
								answerOption: "",
								isAnswer: "N",
                                answerSeq:0,
                                key: Date.now()+Math.random()
							},
							{
								optionSeq: 'B',
								answerOption: "",
								isAnswer: "N",
                                answerSeq:1,
                                key: Date.now()+Math.random()
							}
						]);
					} else {
                        this.questionForm.optionList.forEach((option)=>{
                            option.key = Date.now()+Math.random();
                        });
                    }
				}
			},
            questionForm:{
                immediate:true,
                deep: true,
                handler(val){
                    this.$emit('change',val);
                }
            }
		},
		methods: {
			// 设置选词填空答案
			setAnswer(data) {
                this.$set(this.questionForm,'answer',data.join('※'));
                this.questionForm.optionList.forEach((question)=>{
                    question.isAnswer= "N";
                });
                data.forEach((answer)=>{
                    this.questionForm.optionList.forEach(question=>{
                        if(answer===question.answerOption){
                            question.isAnswer= "Y";
                        }
                    });
                });

				this.isShowSetAnswerDialog = false;
			},
            checkOption(rule, value, callback) {
                if ( value.answerOption === undefined || value.answerOption === ""){
                    return callback(new Error("选项不能为空"));
                }
                const isReceipt = this.questionForm.optionList.some(option=>option.answerOption===value.answerOption && option.optionSeq!==value.optionSeq);
                if( isReceipt) {
                    return callback(new Error("选项不能重复"));
                }
                callback();
            },
			/**
			 * 添加选项
			 */
			add() {
				let length = this.questionForm.optionList.length;
                if(length>=26) {
                    this.$message.warning("最多可添加26个选项");
                    return;
                }
                let len = length + 65;
				this.questionForm.optionList.push({
					optionSeq: String.fromCharCode(len),
					answerOption: "",
					isAnswer: "N",
                    answerSeq:0,
					key: Date.now()
				});
			},
			/**
			 * 删除选项
			 */
			del(index) {
				this.questionForm.optionList.splice(index, 1);
				this.questionForm.optionList.forEach((item, index) => {
					let len = index + 65;
                    item.optionSeq = String.fromCharCode(len);
				});
			},
			// 编辑
			handleEdit(value, key, index) {
				this.$emit("edit", value, key, index);
			},
			//获取题干中的（）数量
			getBracketsNum(str) {
				this.BracketsNum = 0;
				str.replace(/（\s*\)|\(\s*）|\(\s*\)|（\s*）/g, () => {
					// 索引
					this.BracketsNum++;
				});
				return this.BracketsNum;
			},
			isRepeat(arr) {
				let hash = {};
				for (let i in arr) {
					if (hash[arr[i]["answerOption"]]) {
						return true;
					}
					hash[arr[i]["answerOption"]] = true;
				}
				return false;
			},
			// 设置答案弹层，判断题干空格和选项数量
			handleIsShowSetAnswerDialog() {
                this.$refs.answerRef.blur();
				if(this.validateInfo()){
                    this.isShowSetAnswerDialog = true;
                }
			},
            validateInfo(){
                const { questionTitle, optionList } = this.questionForm;
				if (!questionTitle) {
					this.$message.warning("题干不能为空");
					return false;
				}
				if (!this.getBracketsNum(questionTitle)) {
					this.$message.warning("题干必须包含（）");
					return false;
				}
				if (!optionList.every((item) => item.answerOption)) {
					this.$message.warning("选项内容不能为空");
					return false;
				}
				if (optionList && optionList.some(option=>option.answerOption.indexOf("※")!==-1)) {
					this.$message.warning("选项内容不能包含※");
					return false;
				}
				if (this.isRepeat(optionList)) {
					this.$message.warning("选项内容重复");
					return false;
				}
				if (!optionList || this.getBracketsNum(questionTitle) > optionList.length) {
					this.$message.warning("选词填空题的选项数量不能少于（）数量");
					return false;
				}
                return true;
            },
            //校验选项和题干
            api_checkAnswer(){
                const {answer,questionTitle,optionList} = this.questionForm;
                let result = this.validateInfo();
                if(!result){
                    return false;
                }
                let answerResult = answer.split('※');
                if(answerResult.length!==this.getBracketsNum(questionTitle)){
                   this.$message.warning("选词填空题的（）数量和答案数量必须一致");
                    return false;
                }

                if(answerResult.some(answer=>!optionList.find(option=>option.answerOption===answer))){
                   this.$message.warning("答案和选项不符");
                    return false;
                }
                return true;
            }
		}
	};
</script>
<style scoped lang="less">
	.options {
		display: flex;
		flex-direction: row;
	}
	.add-btn {
		margin: 0 10px;
	}
	.m-t15 {
		margin-top: 15px;
	}
	.tips {
		color: #666;
		font-size: 12px;
		line-height: 20px;
		display: block;
	}
	.icons {
		cursor: pointer;
		font-size: 20px;
		margin-top: 7px;
	}
	.options-item {
		margin-bottom: 15px;
		display: flex;
	}
</style>
